@file:Suppress("MemberVisibilityCanBePrivate")

package dev.entao.page

import dev.entao.base.Prop
import dev.entao.base.Prop0
import dev.entao.base.paramNames
import dev.entao.base.userName
import dev.entao.core.HttpContext
import dev.entao.core.controllers.UploadController
import dev.entao.html.*
import kotlin.reflect.full.findAnnotation

class UploadDiv(context: HttpContext) : DivTag(context) {
    val hiddenTag: InputTag
    val resultSpan: SpanTag
    val imgTag: ImageTag
    val progressDiv: DivTag
    val tipSpan: SpanTag

    init {
        this.classAdd("yet-upload-div")
        URL attr context.uriAction(UploadController::upload)
        PARAM attr (UploadController::upload.paramNames.firstOrNull() ?: "file")
        VIEW_URL attr context.uriAction(UploadController::media)
        VIEW_PARAM attr UploadController::media.paramNames.first()
        TYPE_IMAGE_URL attr context.uriAction(UploadController::typeimg)
        TYPE_IMAGE_PARAM attr UploadController::typeimg.paramNames.first()

        hiddenTag = hidden { }
        imgTag = img("yet-upload-image") { }
        progressDiv = div("progress", "yet-upload-progress") {
            div("progress-bar") {
                role = "progressbar"
                style = "width:0%;"
                "aria-valuenow" attr "0"
                "aria-valuemin" attr "0"
                "aria-valuemax" attr "100"
                this.text("0%")
            }
        }
        tipSpan = span("yet-upload-info") {
            +"将文件拖拽到此区域"
        }
        resultSpan = span("yet-upload-result") { }

        script {
            """
                client.bindUploadById('${this.idx}');
            """.trimIndent()
        }

    }

    fun fromProp(prop: Prop) {
        SIZE_LIMIT_M attr (prop.findAnnotation<RefUpload>()?.limitSizeM ?: 0).toString()
        hiddenTag.name = prop.userName
        hiddenTag.value = valueOf(prop) ?: ""
        if (prop is Prop0) {
            resultSpan.text(prop.displayString(null))
        }

    }

    companion object {
        private const val SIZE_LIMIT_M = "data-upload-limit-m"
        private const val URL = "data-upload-url"
        private const val PARAM = "data-upload-param"
        private const val VIEW_URL = "data-upload-view-url"
        private const val VIEW_PARAM = "data-upload-view-param"
        private const val TYPE_IMAGE_URL = "data-upload-type-image-url"
        private const val TYPE_IMAGE_PARAM = "data-upload-type-image-param"
    }
}